from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from oauth.models import OauthQQUser
from oauth.utils import OAuthQQ
from users.models import User


class OauthQQUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='操作凭证', write_only=True)  # 从用户处接收的token
    token = serializers.CharField(read_only=True)  # 返回给用户的token
    # 重写mobile字段  进行简单的格式验证
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'sms_code', 'token', 'mobile', 'access_token']
        extra_kwargs = {
            "password": {
                "write_only": True
            },
            "username": {
                "read_only": True
            }
        }

    def validate(self, attrs):
        """分析:这个校验里需要实现的功能
        0.校验accesstoken,并解密出openid  设置attrs['openid']=openid
        1.校验短信验证码
        1.检测用户是否存在,如果存在且密码正确,设置attrs['user']=查出来的user
        2.如果不正确 return
        """
        # 校验access_token  实际上就是解密后校验openid
        access_token = attrs.get('access_token')
        # 在oauth模型中定义静态方法解密openid  如果不对返回None
        openid = OAuthQQ.check_user_access_token(access_token)

        if not openid:
            raise serializers.ValidationError('无效的access_token')

        attrs['openid']=openid
        # 校验短信验证码
        redis_conn = get_redis_connection('verify_code')
        real_sms_code = redis_conn.get('sms_%s' % attrs['mobile']).decode()
        if real_sms_code != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')

        # 检测用户是否存在
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except User.DoesNotExist:
            # 如果用户不存在 不返回用户相关的东西
            pass
        else:
            # 如果用户存在 此时进行密码校验
            if not user.check_password(attrs['password']):
                # 校验成功说明已有用户  将user作为attrs的属性返回
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # validated_data中包含了attrs中校验过的数据,包括动态添加的数据
        openid = validated_data['openid']
        user = validated_data.get('user')
        mobile = validated_data['mobile']
        password = validated_data['password']

        # 如果用户不存在  先创建用户  再创建qquser
        if not user:
            User.objects.create_user(username=mobile, mobile=mobile, password=password)

        # 创建qquser
        OauthQQUser.objects.create(user=user, openid=openid)

        # 此时绑定已经完成 返回user给前端以做其他处理 ,同时签发token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
